'use strict';
/*
 * 数据库连接ORM ,定义表字段，表间的关系，
 */

var router    = require('express').Router();
var ErrorCode = require('./sqlapis/err');
var User      = require('./sqlapis/api_users');
var Sms 	  = require('./sqlapis/api_sms');

//用户注册发送验证码
router.post('/sendVcode',SendCodeCheckIfUserExit,function(req, res){
	var data = {
		mobile:req.body.mobile
	}
	Sms.sendVcode(data,function(result){		
		res.send(result);
	})
})

//用户注册发送验证码
router.post('/sendCheckVcode',function(req, res){
	var data = {
		mobile:req.body.mobile
	}
	Sms.sendVcode(data,function(result){		
		res.send(result);
	})
})

//用户注册
router.post('/checkVcode',function(req, res){
	var data = {
		key:req.body.mobile,
		text:req.body.code
	}
	Sms.checkVcode(data,function(result){	
		var data={
			code:'1',
			message:'success',
			datas:result
		}	
		res.send(data);
	})
})

//修改密码发送验证码
router.post('/changePassCode',SendPassCodeCheckIfUserExit,function(req,res){
	var data = {
		mobile:req.body.mobile
	}
	if(req.body.mobile){
		Sms.sendPasswordVcode(data,function(err,result){	
			if(err){
				res.send(err)
			}else{
				res.send(result);
			}	
			
		})
	}else{
		res.send(ErrorCode.noMobile);
	}
})

function SendPassCodeCheckIfUserExit(req, res, next){
  var mobile = req.body.phoneNo||req.body.mobile;
  if(mobile)
  {
    Promise.all([
      checkWithOneParam('mobile_phone',mobile),
    ]).then(function(r0){
      if(r0[0] != '1'){
        res.send(ErrorCode.canNotFindUser);
      }
      else{
        next();
      }
    })
  }
  else{
    res.send(ErrorCode.canNotFindUser);
  }
}

//发送验证码时检查当前用户是否存在
function SendCodeCheckIfUserExit(req, res, next){
	var mobile = req.body.mobile;
	if( !mobile)
	{
		res.send(ErrorCode.noMobile);
	}
	else{
		Promise.all([
			checkWithOneParam('mobile_phone',mobile),
		]).then(function(r0){
			if(req.body.changePass){
				if(r0 != '1'){
					res.send(ErrorCode.canNotFindUser);
				}
				else{
					next();
				}
			}else{
				if(r0 == '1'){
					res.send(ErrorCode.sameMobile);
				}
				else{
					next();
				}
			}
		})
	}
}

//根据一个参数检测用户是否存在
function checkWithOneParam(key,text){
	var promise = new AV.Promise(function(resolve,reject){
		var data = {
			key : key,
			text: text
		}
		User.checkIfUserExit(data,function(result){
			resolve(result);
		});
	});
	return promise;
}

module.exports = router;
module.exports.checkWithOneParam = checkWithOneParam;
